package com.cupk.inspection.controller;

import com.cupk.inspection.model.User;
import com.cupk.inspection.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/users")
@CrossOrigin(origins = "*")
public class UserController {

    @Autowired
    private UserService userService;

    // 添加用户
    @PostMapping("/addUser")
    public ResponseEntity<String> addUser(@RequestBody User user) {
        if (user.getUsername() == null || user.getPassword() == null || user.getRole() == null) {
            return ResponseEntity.badRequest().body("Username, password, and role are required");
        }
        userService.addUser(user);
        return ResponseEntity.ok("User added successfully");
    }

    // 查询用户
    @GetMapping("/selectUser/{id}")
    public ResponseEntity<User> selectUser(@PathVariable Long id) {
        Optional<User> user = userService.selectUser(id);
        return user.map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    // 删除用户
    @DeleteMapping("/deleteUser/{id}")
    public ResponseEntity<String> deleteUser(@PathVariable Long id) {
        if (!userService.existsById(id)) {
            return ResponseEntity.notFound().build();
        }
        userService.deleteUser(id);
        return ResponseEntity.ok("User deleted successfully");
    }

    // 更新用户
    @PutMapping("/updateUser/{id}")
    public ResponseEntity<String> updateUser(@PathVariable Long id, @RequestBody User user) {
        if (user.getUsername() == null || user.getPassword() == null || user.getRole() == null) {
            return ResponseEntity.badRequest().body("Username, password, and role are required");
        }
        if (!userService.existsById(id)) {
            return ResponseEntity.notFound().build();
        }
        userService.updateUser(id, user);
        return ResponseEntity.ok("User updated successfully");
    }
    // 获取用户列表
    @GetMapping("/getUserAll")
    public ResponseEntity<List<User>> getUserAll() {
        List<User> users = userService.getAllUsers();
        if (users.isEmpty()) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(users);
    }
    // 登录
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody User user) {
        if (user.getUsername() == null || user.getPassword() == null) {
            return ResponseEntity.badRequest().body(Map.of("success", false, "message", "Username and password are required"));
        }
        Optional<User> existingUser = userService.selectUserByUsername(user.getUsername());
        if (!existingUser.isPresent()) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of("success", false, "message", "User not found"));
        }
        User foundUser = existingUser.get();
        if (!foundUser.getPassword().equals(user.getPassword())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of("success", false, "message", "Password is incorrect"));
        }
        return ResponseEntity.ok(Map.of("success", true, "message", "Login successful", "user", foundUser));
    }

    // 注册
    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> register(@RequestBody User user) {
        Map<String, Object> responseMap = new HashMap<>();
        user.setRole("巡检员");
        if (user.getUsername() == null || user.getPassword() == null || user.getRole() == null) {
            responseMap.put("success", false);
            responseMap.put("message", "Username, password, and role are required");
            return ResponseEntity.badRequest().body(responseMap);
        }
        if (userService.existsByUsername(user.getUsername())) {
            responseMap.put("success", false);
            responseMap.put("message", "Username already exists");
            return ResponseEntity.badRequest().body(responseMap);
        }
        userService.addUser(user);
        responseMap.put("success", true);
        responseMap.put("message", "User registered successfully");
        return ResponseEntity.ok(responseMap);
    }
}